using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace Tarea5
{
    partial class ViewGUI : Form, ViewInterface, ObserverInterface
    {
        // Variables
        TableLayoutPanel catsGame;
        Label[] lbSquare;
        private ControllerInterface controller;
        private ModelInterface model;
        private const int cDefaultSize = 3;
        private const int DefaultSpeed = 50;
        private Image humanImage,macImage,whumanImage,wmacImage;
        private bool blWinner;

        public ViewGUI()
        {
            InitializeComponent();
            cmbModel.SelectedIndex = 0;
            cmbDepth.SelectedIndex = 0;
            Form.CheckForIllegalCrossThreadCalls = false;            
        }

        #region Model
        /// Start region for Model
        public void Initialize(string title, ControllerInterface controller)
        {
            this.controller = controller;
            this.Text = "Tic Tac Toe Interactive";
            Application.Run((Form)this);            
        }

        public void SetModel(string title, ModelInterface model)
        {
            if (this.model != null)
                model.RemoveObserver(this);
            this.model = model; 
            this.Text = title;
            model.RegisterObserver(this);
        }

        public void Update(StateInterface state, string msg, string info)
        {      
            lbMsg.Text = msg;
            if (!blWinner)
            {
                if (state.IsWon != 0)
                {
                    blWinner = true; Winner(state.Board, state.IsWon);
                    for (int i = 0; i < cDefaultSize * cDefaultSize; i++)
                        if (lbSquare[i].Image == null)
                            lbSquare[i].Enabled = false;
                }
                else
                    updateBoard(state.Board, state);
            }
        }

        private void Winner(int[,] board, int w)
        {
            Image wIm = null;
            String wMsg = "Human has won";

            if (w == 1 && cbHFirst.Checked || w == 2 && !cbHFirst.Checked) // gano humano
            {
                wIm = whumanImage;
                wMsg = "Human has won";
            }
            else if (w == 1 && !cbHFirst.Checked || w == 2 && cbHFirst.Checked) // gano maq                
            {
                wIm = wmacImage;
                wMsg = "Computer has won";
            }
            
            int r = 0;
            int c = 0;
            int d1 = 0;
            int d2 = 0;
            int j = 0;
            int i = 0;

            while (i < cDefaultSize && r != cDefaultSize && c != cDefaultSize && d1 != cDefaultSize && d2 != cDefaultSize)
            {
                r = 0;
                c = 0;
                j = 0;

                while (j < cDefaultSize && r != cDefaultSize && c != cDefaultSize && d1 != cDefaultSize && d2 != cDefaultSize)
                {
                    if (board[i, j] == w)
                        r++;
                    if (board[j, i] == w)
                        c++;
                    if (board[i, j] == w && i == j) // main diag
                        d1++;
                    if (board[i, j] == w &&  i + j == cDefaultSize - 1) // the other diag
                        d2++;
                    
                    j++;
                }
                i++;
            }

            if (r == cDefaultSize) // gano en renglon i
                for (int k = 0; k < cDefaultSize; k++)
                    lbSquare[(i - 1) * cDefaultSize + k].Image = wIm;
            else if (c == cDefaultSize) // gano en columna i
                for (int k = 0; k < cDefaultSize; k++)
                    lbSquare[(k) * cDefaultSize + (i - 1)].Image = wIm;
            else if (d1 == cDefaultSize) // gano en \
                for (int k = 0; k < cDefaultSize; k++)
                    for (int t = 0; t < cDefaultSize; t++)
                    {
                        if (k == t)
                            lbSquare[(k) * cDefaultSize + t].Image = wIm;
                    }                    
            else if (d2 == cDefaultSize) // gano en /
                for (int k = 0; k < cDefaultSize; k++)
                    for (int t = 0; t < cDefaultSize; t++)
                    {
                        if (k + t == cDefaultSize -1)
                            lbSquare[(k) * cDefaultSize + t].Image = wIm;
                    }
           // andTheWinnerIs(wMsg);
        }

        private void updateBoard(int[,] board, StateInterface state)
        {
          for (int i = 0;i<cDefaultSize;i++)
              for (int j = 0; j < cDefaultSize; j++)
              {
                  if (cbHFirst.Checked && board[i,j] != 0) // empezo primero humano
                  {
                      if (board[i, j] == 1)
                          lbSquare[i * cDefaultSize + j].Image = humanImage;
                      else
                          lbSquare[i * cDefaultSize + j].Image = macImage;
                  }
                  else if (!cbHFirst.Checked && board[i, j] != 0)
                  {
                      if (board[i, j] == 1)
                          lbSquare[i * cDefaultSize + j].Image = macImage;
                      else
                          lbSquare[i * cDefaultSize + j].Image = humanImage;
                  }
              }        
        }


        private void andTheWinnerIs(String winner)
        {            
          MessageBox.Show(winner,"Game Over",MessageBoxButtons.OK,MessageBoxIcon.Information);
        }

        /// End region for Model
        #endregion

        #region Form Components
        /// Start region for Form Components
        public void buildCat()
        {                       
            catsGame = new TableLayoutPanel();
            catsGame.Hide();
            catsGame.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
            | System.Windows.Forms.AnchorStyles.Left)
            | System.Windows.Forms.AnchorStyles.Right)));
            catsGame.AutoSize = false;
            catsGame.CellBorderStyle = System.Windows.Forms.TableLayoutPanelCellBorderStyle.Inset;
            catsGame.ColumnCount = cDefaultSize;
            for (int i = 0; i < catsGame.ColumnCount; i++)
            {
                this.catsGame.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, ((catsGame.Width / cDefaultSize) * 100) / catsGame.Width));
            }
            this.catsGame.Location = new System.Drawing.Point(55, 3);
            this.catsGame.Name = "tablero";
            this.catsGame.RowCount = cDefaultSize;
            for (int i = 0; i < catsGame.ColumnCount; i++)
            {
                this.catsGame.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, ((catsGame.Height / cDefaultSize) * 100) / catsGame.Width));
            }
            this.catsGame.Size = new System.Drawing.Size(485,485); // 485
            this.catsGame.TabIndex = 0;
            this.catsGame.Location = new System.Drawing.Point(25, 41);
            this.splitContainer1.Panel2.Controls.Clear();
            this.splitContainer1.Panel2.Controls.Add(catsGame);            
            addLabels();
            catsGame.Show();
        }

        public void lbSquares_Click(object sender, EventArgs e)
        {           
            for (int i=0;i<lbSquare.Length;i++)
                if (sender == lbSquare[i] && lbSquare[i].Image == null)
                    model.SetPosition(i / cDefaultSize, i % cDefaultSize);                
        }

        public void addLabels()
        {
            catsGame.Hide();
            catsGame.Controls.Clear();
            lbSquare = new Label[cDefaultSize*cDefaultSize];

            for (int k = 0; k < lbSquare.Length; k++)
                {             
                    lbSquare[k] = new Label();
                    lbSquare[k].Click += new System.EventHandler(lbSquares_Click);
                    /// format Label
                    lbSquare[k].FlatStyle = System.Windows.Forms.FlatStyle.Flat;
                    lbSquare[k].ForeColor = System.Drawing.SystemColors.ActiveCaptionText;
                    lbSquare[k].Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                            | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right)));
                    lbSquare[k].AutoSize = true;
                    lbSquare[k].Location = new System.Drawing.Point(1, 1);
                    lbSquare[k].Name = "tiles" + k;
                    lbSquare[k].Size = new System.Drawing.Size(75, 23);
                    lbSquare[k].Font = new System.Drawing.Font("Microsoft Sans Serif", 20F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                    ///
                    catsGame.Controls.Add(lbSquare[k]);                    
                }
        }

        private void btnStart_Click(object sender, EventArgs e) //jf
        {         
            if (btnStart.Text.Equals("Start"))
                {
                    cmbModel.Enabled = false;
                    cmbDepth.Enabled = false;
                    rBCrosses.Enabled = false;
                    rBNaughts.Enabled = false;
                    cbHFirst.Enabled = false;
                    btnStart.Text = "Reset";
                }
            else
                {
                    cmbModel.Enabled = true;
                    cmbDepth.Enabled = true;
                    rBCrosses.Enabled = true;
                    rBNaughts.Enabled = true;
                    cbHFirst.Enabled = true;
                    btnStart.Text = "Start";
                    splitContainer1.Panel2.Controls.Clear();
                    lbMsg.Text = "";
                    return;
                }

            buildCat();
            blWinner = false;            
            
            if (rBNaughts.Checked) { humanImage = imagesBoard.Images[0]; macImage = imagesBoard.Images[1]; whumanImage = imagesBoard.Images[2]; wmacImage = imagesBoard.Images[3]; }// seleccion de imagen
            else { humanImage = imagesBoard.Images[1]; macImage = imagesBoard.Images[0]; whumanImage = imagesBoard.Images[3]; wmacImage = imagesBoard.Images[2]; };

            Behaviors.Behavior behavior = Behaviors.Behavior.TTTHRMC;
            switch (cmbModel.SelectedIndex)
	        {
                case 0:
                    behavior = Behaviors.Behavior.TTTHRMC;
                    break;
                case 1:
                    behavior = Behaviors.Behavior.TTTHSRMC;
                    break;
                case 2:
                    behavior = Behaviors.Behavior.TTTHSC;
                    break;
                case 3:
                    behavior = Behaviors.Behavior.TTTHCAB;
                    break;
	        }

            short[,] temp = new short[cDefaultSize, cDefaultSize];                      
            controller.SetModel(behavior, DefaultSpeed, temp, cbHFirst.Checked, cDefaultSize, cmbDepth.SelectedIndex + 1);
            controller.Start();            
        }
        private void btnReset_Click(object sender, EventArgs e)
        {
           this.splitContainer1.Panel2.Controls.Clear();            
        }                
        private void btnUndo_Click(object sender, EventArgs e)
        {
            //controller.UnDoMoveCell();
        }

        private void cbHFirst_CheckedChanged(object sender, EventArgs e)
        {                
        }

        /// End region for model
        #endregion
    }    
}